package com.topvision.camerasdk.album;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.topvision.camerasdk.DocumentActivity;
import com.topvision.camerasdk.R;
import com.topvision.camerasdk.album.adapter.PhotoGridAdapter;
import com.topvision.camerasdk.camera.CameraConstants;
import com.topvision.camerasdk.camera.util.CameraUtil;
import com.topvision.camerasdk.video.MediaRecorderActivity;
import com.topvision.camerasdk.video.PlayVideoActivity;
import com.topvision.camerasdk.video.util.VideoConstant;
import com.topvision.commomsdk.TouchInterface;
import com.topvision.commomsdk.commom.Album;
import com.topvision.commomsdk.uitl.AndroidUtils;
import com.topvision.commomsdk.uitl.DocConversionUtil;
import com.topvision.commomsdk.view.TvGridView;
import com.topvision.voicesdk.BaseVoiceActivity;
import com.topvision.voicesdk.CommonVoice;
import com.topvision.voicesdk.VoiceInterface;

import java.util.ArrayList;


/**
 * 照片列表类
 *
 * @author jack
 *         create at 2016/11/21 16:38
 */
public class MyAblumActivity extends BaseVoiceActivity implements TouchInterface, VoiceInterface {
    //更新相冊
    public static final String ACTION_UPDATE_ALBUM = "action_update_album";
    private static final int REQUEST_CODE = 10001;
    //照片集合控件
    private TvGridView photoGridView;
    //所有照片集合
    ArrayList<Album> list;
    //當前位置
    private int positionTag = 0;
    private PhotoGridAdapter photoGridAdapter;
    //前滑操作
    private final int forward = 1;
    //后滑操作
    private final int doBACK = 0;
    private final int doInitData = 2;
    Context context;
    MyReceiver myReceiver;
    //照片分页操作变量
    int currentPage = 1;
    int totalPage = 0;
    //一页显示几个
    int pageSize = 8;
    int startIndex = 0;
    int endIndex = 0;
    //当前页的照片列表
    ArrayList<Album> pageList;
    TextView voiceTips;
    boolean voiceTipFlag;

    /******
     * 12.13
     *****/
    String ablumType;
    String FolderPath;
    /******
     * End
     *****/
    //是否轮播标示
    boolean video_Carousel = false;
    RelativeLayout circleProgressRel;
    private TextView ablumPage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);// 强制为横屏
        setContentView(R.layout.activity_camera_my_ablum);
        context = this;
        initUi();
        initData();
        registerMyReceiver();
    }


    /**
     * 初始化数据
     *
     * @author jack
     * create at 2016/11/21 16:49
     */
    private void initData() {
        /******    12.13      *****/
        ablumType = getIntent().getStringExtra(VideoConstant.ABLUM_TYPE);
        if (ablumType.equals(VideoConstant.ABLUM_TYPE_MEDIA)) {
            FolderPath = MediaRecorderActivity.TAKE_VIDEO_FOLDER;
        } else if (ablumType.equals(VideoConstant.ABLUM_TYPE_PHOTO)) {
            FolderPath = CameraConstants.TAKE_PHOTO_FOLDER;
        }
        String path = getIntent().getStringExtra(CameraConstants.SAVE_PATH);
        if (!TextUtils.isEmpty(path)) {
            FolderPath = path;
            MediaRecorderActivity.TAKE_VIDEO_FOLDER = FolderPath;
            video_Carousel = true;
        }
        /******    End      *****/
        list = new ArrayList<Album>();
        //异步加载照片列表
        new PhotoLoadTask(this, doInitData).execute();
    }

    /**
     * 初始化
     *
     * @author jack
     * create at 2016/11/21 16:48
     */
    private void initUi() {
        //覆盖GridView自身的touch事件
        photoGridView = (TvGridView) findViewById(R.id.photoGridView);
        voiceTips = (TextView) findViewById(R.id.my_ablum_voice_tips);
        voiceTipFlag = getIntent().getBooleanExtra(CameraConstants.VOICE_TIPS_FLAG, true);
        if (!voiceTipFlag) {
            voiceTips.setVisibility(View.GONE);
        }
        circleProgressRel = (RelativeLayout) findViewById(R.id.circle_progress_rel);
        //页码
        ablumPage = (TextView) findViewById(R.id.ablum_page);

        //BT300点击事件
        if (AndroidUtils.isBtDevice()) {
            photoGridView.setNoScroll(false);
            photoGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Album album = (Album) parent.getAdapter().getItem(position);
                    whenItemClicked(album, position);
                }
            });
            photoGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                    //切换成按钮操作
                    photoGridView.setNoScroll(true);
                    AndroidUtils.showTips(MyAblumActivity.this, "当前模式:按钮模式");
                    photoGridAdapter.showBackGround();
                    return true;
                }
            });
        } else {
            photoGridView.setNoScroll(true);
        }
    }

    private void whenItemClicked(Album album, int position) {
        if (pageList == null) {
            return;
        }
        if (pageList.size() == 0) {
            return;
        }

        /******    12.13   *****/
        if (ablumType.equals(VideoConstant.ABLUM_TYPE_MEDIA)) {
            String path = album.getFile().getPath();
            Intent playVideoIntent = new Intent(MyAblumActivity.this, PlayVideoActivity.class);
            playVideoIntent.putExtra(CameraConstants.VOICE_TIPS_FLAG, voiceTipFlag);
            playVideoIntent.putExtra(VideoConstant.PLAY_VIDEO_CAROUSEL, true);
            playVideoIntent.putParcelableArrayListExtra(VideoConstant.ALBUM_KEY, pageList);
            playVideoIntent.putExtra(PhotoGridAdapter.CURRENT_POSITON, position);
            playVideoIntent.putExtra(VideoConstant.PLAY_VIDEO_PATH, path);
            startActivityForResult(playVideoIntent, REQUEST_CODE);
//            startActivity(playVideoIntent);

        } else if (ablumType.equals(VideoConstant.ABLUM_TYPE_PHOTO)) {
            String path = album.getFile().getPath();
            if (path.endsWith(".doc")
                    || path.endsWith(".xls")
                    || path.endsWith(".pdf")) {

                Intent DocumentIntent = new Intent(MyAblumActivity.this, DocumentActivity.class);
                DocumentIntent.putExtra(DocConversionUtil.DOC_FILE_PATH, path);
                startActivity(DocumentIntent);

            } else {
                Intent showPicIntent = new Intent(MyAblumActivity.this, ShowPicActivity.class);
                showPicIntent.putExtra(CameraConstants.VOICE_TIPS_FLAG, voiceTipFlag);
                showPicIntent.putParcelableArrayListExtra(VideoConstant.ALBUM_KEY, pageList);
                showPicIntent.putExtra(PhotoGridAdapter.CURRENT_POSITON, position);
                startActivity(showPicIntent);
            }
        }
        photoGridAdapter.upData(positionTag);
        /******    End  *****/

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterMyReceiver();
    }

    protected void onResume() {
        super.onResume();
        setTouchInterfaceListener(this);
        setVoiceInterfaceListener(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        setTouchInterfaceListener(null);
        setVoiceInterfaceListener(null);
    }

    ;

    @Override
    public void doForwardTouch() {
        stateTag(forward);
    }

    @Override
    public void doBackwardTouch() {
        stateTag(doBACK);
    }

    @Override
    public void doClickTouch() {
        if (isBackUpData) {
            if (updataComplete) {
                isBackUpData = false;
                doClick();
            }
            return;
        } else {
            doClick();
        }
    }

    @Override
    public void doDoubleTouch() {
        //BT300的切换模式操作
        if (AndroidUtils.isBtDevice()) {
            //切换成点击操作
            photoGridView.setNoScroll(false);
            photoGridAdapter.hideBackGround();
            AndroidUtils.showTips(this,"当前模式:点击模式");
        }
    }

    private void stateTag(int tag) {
        if (list.size() == 0) {
            return;
        }
        switch (tag) {
            case doBACK:
                doBack();
                break;
            case forward:
                doForward();
                break;
        }
    }

    /**
     * 向上
     *
     * @author jack
     * create at 2016/11/22 13:15
     */
    private void doBack() {
        if (AndroidUtils.isBtDevice()) {
            // BT300 直接翻页
            if (currentPage > 1) {
                new PhotoLoadTask(this, doBACK).execute();
            }
        } else {
            if (list != null && list.size() > 0) {
                if (positionTag > 0) {
                    positionTag--;
                    photoGridAdapter.upData(positionTag);
                } else {
                    //当当前页面填满一页时,执行翻页操作,未填满则不进行任何操作
                    if (currentPage > 1) {
                        new PhotoLoadTask(this, doBACK).execute();
                    }
                }
            }
        }
    }

    /**
     * 向下
     *
     * @author jack
     * create at 2016/11/22 13:15
     */
    private void doForward() {
        if (AndroidUtils.isBtDevice()) {
            // BT300 直接翻页
            if (pageList != null && pageList.size() >= pageSize) {
                new PhotoLoadTask(this, forward).execute();
            }
        } else {
            if (list != null && list.size() > 0) {
                if (positionTag + 1 < pageList.size()) {
                    positionTag++;
                    photoGridAdapter.upData(positionTag);
                } else {
                    //当当前页面填满一页时,执行翻页操作,未填满则不进行任何操作
                    if (pageList != null && pageList.size() >= pageSize) {
                        new PhotoLoadTask(this, forward).execute();
                    }

                }
            }
        }
    }

    private void doClick() {
        if (pageList == null) {
            return;
        }
        if (pageList.size() == 0) {
            return;
        }

        /******    12.13   *****/
        if (ablumType.equals(VideoConstant.ABLUM_TYPE_MEDIA)) {
            String path = list.get(positionTag).getFile().getPath();
            Intent playVideoIntent = new Intent(MyAblumActivity.this, PlayVideoActivity.class);
            playVideoIntent.putExtra(CameraConstants.VOICE_TIPS_FLAG, voiceTipFlag);
            playVideoIntent.putExtra(VideoConstant.PLAY_VIDEO_CAROUSEL, true);
            playVideoIntent.putParcelableArrayListExtra(VideoConstant.ALBUM_KEY, pageList);
            playVideoIntent.putExtra(PhotoGridAdapter.CURRENT_POSITON, positionTag);
            playVideoIntent.putExtra(VideoConstant.PLAY_VIDEO_PATH, path);
            startActivityForResult(playVideoIntent, REQUEST_CODE);
//            startActivity(playVideoIntent);

        } else if (ablumType.equals(VideoConstant.ABLUM_TYPE_PHOTO)) {
            String path = list.get(positionTag).getFile().getPath();
            if (path.endsWith(".doc")
                    || path.endsWith(".xls")
                    || path.endsWith(".pdf")) {

                Intent DocumentIntent = new Intent(MyAblumActivity.this, DocumentActivity.class);
                DocumentIntent.putExtra(DocConversionUtil.DOC_FILE_PATH, path);
                startActivity(DocumentIntent);

            } else {
                Intent showPicIntent = new Intent(MyAblumActivity.this, ShowPicActivity.class);
                showPicIntent.putExtra(CameraConstants.VOICE_TIPS_FLAG, voiceTipFlag);
                showPicIntent.putParcelableArrayListExtra(VideoConstant.ALBUM_KEY, pageList);
                showPicIntent.putExtra(PhotoGridAdapter.CURRENT_POSITON, positionTag);
                startActivity(showPicIntent);
            }


        }
        photoGridAdapter.upData(positionTag);
        /******    End  *****/

    }

    /**
     * 回调方法
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case RESULT_OK:
                doClick();
                break;
        }
    }

    @Override
    public void dealWithVoice(String data) {
        data = data.toLowerCase();
        if (CommonVoice.VOICE_ZH_BACK.equals(data) || CommonVoice.VOICE_US_BACK.equalsIgnoreCase(data)) {
            this.finish();
        } else if (CommonVoice.VOICE_ZH_UP.equals(data) || CommonVoice.VOICE_US_UP.equalsIgnoreCase(data)) {
            doBackwardTouch();
        } else if (CommonVoice.VOICE_ZH_DOWN.equals(data) || CommonVoice.VOICE_US_DOWN.equalsIgnoreCase(data)) {
            doForwardTouch();
        } else if (CommonVoice.VOICE_ZH_OK.equals(data) || CommonVoice.VOICE_US_OK.equalsIgnoreCase(data) || CommonVoice.VOICE_US_CONFIRM.equalsIgnoreCase(data)) {
            doClickTouch();
        } else if (CommonVoice.VOICE_ZH_NEXT_PAGE.equals(data)) {
            //下一页
            if (pageList != null && pageList.size() >= pageSize) {
                new PhotoLoadTask(this, forward).execute();
            }
        } else if (CommonVoice.VOICE_ZH_PREVIOUS_PAGE.equals(data)) {
            //上一页
            if (currentPage > 1) {
                new PhotoLoadTask(this, doBACK).execute();
            }
        }
    }
    private boolean isBackUpData;
    class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_UPDATE_ALBUM.equals(action)) {
                //更新数据就可以了
                isBackUpData = true;
                circleProgressRel.setVisibility(View.VISIBLE);
                updateAlbumList();
            }
        }
    }

    /**
     * 更新相冊列表
     *
     * @author jack
     * create at 2016/11/23 11:56
     */
    private void updateAlbumList() {
        if (positionTag > 0) {
            positionTag = positionTag - 1;
        }
        new PhotoLoadTask(this, doInitData).execute();
    }

    /**
     * 注册广播
     *
     * @author jack
     * create at 2016/11/23 12:58
     */
    private void registerMyReceiver() {
        if (myReceiver == null) {
            myReceiver = new MyReceiver();
        }
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_UPDATE_ALBUM);
        registerReceiver(myReceiver, intentFilter);
    }

    /**
     * 解除广播
     *
     * @author jack
     * create at 2016/11/23 12:58
     */
    private void unRegisterMyReceiver() {
        if (myReceiver != null) {
            unregisterReceiver(myReceiver);
        }
    }


    /**
     * @author (Joker)
     * @version V1.0
     * @ClassName: GridViewLoadTask
     * @Description: TODO(这里用一句话描述这个类的作用)
     * @date 2016-8-25 下午4:50:52
     */
    private boolean updataComplete;
    public class PhotoLoadTask extends AsyncTask<Integer, Integer, String> {
        //后面尖括号内分别是参数（线程休息时间），进度(publishProgress用到)，返回值 类型
        private Context mContext = null;
        int type;

        public PhotoLoadTask(Context context, int type) {
            updataComplete = false;
            this.mContext = context;
            this.type = type;

        }

        /*
         * 第一个执行的方法
         * 执行时机：在执行实际的后台操作前，被UI 线程调用
         * 作用：可以在该方法中做一些准备工作，如在界面上显示一个进度条，或者一些控件的实例化，这个方法可以不用实现。
         * @see android.os.AsyncTask#onPreExecute()
         */
        @Override
        protected void onPreExecute() {
            circleProgressRel.setVisibility(View.VISIBLE);
            super.onPreExecute();
        }


        /*
         * 执行时机：在onPreExecute 方法执行后马上执行，该方法运行在后台线程中
         * 作用：主要负责执行那些很耗时的后台处理工作。可以调用 publishProgress方法来更新实时的任务进度。该方法是抽象方法，子类必须实现。
         * @see android.os.AsyncTask#doInBackground(Params[])
         */
        @Override
        protected String doInBackground(Integer... params) {
            try {
                //当list为空时,或者主动需要重新拉取数据时,获取相册列表
                if (list == null || (list != null && list.size() == 0) || type == doInitData) {
                    /**************  12.13  ********************/
                    if (ablumType.equals(VideoConstant.ABLUM_TYPE_MEDIA)) {
                        list = CameraUtil.getVideoList(context);
                    } else if (ablumType.equals(VideoConstant.ABLUM_TYPE_PHOTO)) {
                        list = CameraUtil.getPhotoList(context);
                    }
                    totalPage = list.size() / pageSize + (list.size() % pageSize == 0 ? 0 : 1);
                    System.out.println("文件总个数：" + list.size() + ",总页数：" + totalPage + ",余值：" + ((list.size() % 8) == 0 ? 0 : 1));
                    System.out.println(positionTag + "--" + list.size());
                    if (list.size() % pageSize == 0 && currentPage > 1) {
                        currentPage--;
                    }
                    /*************** End  *******************/

                }
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
            return "success";

        }


        /*
         * 执行时机：在doInBackground 执行完成后，将被UI 线程调用
         * 作用：后台的计算结果将通过该方法传递到UI 线程，并且在界面上展示给用户
         * result:上面doInBackground执行后的返回值，所以这里是"执行完毕"
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */


        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            circleProgressRel.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(result)) {
                //前滑到最后一张图片上
                if (type == forward) {
                    currentPage++;
                    positionTag = 0;
                }
                //后滑翻页操作
                else if (type == doBACK) {
                    currentPage--;
                    positionTag = pageSize - 1;
                } else if (type == doInitData) {

                }
                //临时存放相册列表
                ArrayList<Album> tempList = pageList;
                pageList = new ArrayList<>();
                startIndex = (currentPage - 1) * pageSize;
                endIndex = startIndex + pageSize - 1;
                for (int i = startIndex; i <= endIndex; i++) {
                    try {
                        Album album = list.get(i);
                        if (album != null) {
                            pageList.add(album);
                        }
                    } catch (Exception e) {
                    }
                }

                //第一次加载
                if (type == doInitData) {
                    //只初始化一次
                    if (photoGridAdapter == null) {
                        /********** 12.13 ***************/
                        photoGridAdapter = new PhotoGridAdapter(mContext, pageList, ablumType, voiceTipFlag);
                        /********** End ***************/
                        //photoGridAdapter = new PhotoGridAdapter(mContext, pageList );
                        photoGridView.setAdapter(photoGridAdapter);
                    } else {
                        photoGridAdapter.upDataList(positionTag, pageList);
                    }

                    //翻页操作更新数据
                } else if (type == forward || type == doBACK) {
                    //当翻页操作没有数据的时候回滚数据
                    if (pageList.size() == 0 && type == forward) {
                        pageList = tempList;
                        currentPage--;
                        positionTag = pageSize - 1;
                    } else if (pageList.size() == 0 && type == doBACK) {
                        pageList = tempList;
                        currentPage++;
                        positionTag = 0;
                    } else {
                        photoGridAdapter.upDataList(positionTag, pageList);
                    }

                }

            }
            updataComplete = true;
            circleProgressRel.setVisibility(View.GONE);
            ablumPage.setText(currentPage + "/" + totalPage);
        }

    }

}
